// pages/chat/chat.ts
import { isLogin, login } from '../../utils/login'
import { getTrainTaskList } from '../../api/train'

Page({
  /**
   * 页面的初始数据
   */
  data: <any>{
    id: '',
    title: '',
    active: 1,
    allList: [],
    filterList: [],
    nextList: [],
    statusEnum: {
      'INCOMPLETE': 'unfinished',
      'COMPLETE': 'finished',
      'REJECT': 'rejected'
    },
    btnEnum: {
      'INCOMPLETE': '开始',
      'COMPLETE': '已完成',
      'REJECT': '驳回重训'
    }
  },

  onLoad(options){
    this.setData({
      title: options.title
    })
  },

  onShow(){
    this.init()
  },

  init(){
    const _self = this
    if(isLogin()){
      const userInfo = login()
      if(userInfo){
        this.handleLoginAction(userInfo);
      }

      if(this.data.id){
        getTrainTaskList({
          projectId: this.data.id,
          type: _self.data.active
        }).then(res => {
          if(res && res.rows){
            _self.setData({
              allList: res.rows,
              filterList: res.rows,
              nextList: res.rows.filter(item => item.taskStatus !== "COMPLETE").map(item => item.id)
            })
          }
        })
      }

      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('acceptDataFromOpenerPage', function(data) {
        if(data){
          _self.setData({
            id: data.id
          })
          getTrainTaskList({
            projectId: data.id,
            type: _self.data.active
          }).then(res => {
            if(res && res.rows){
              _self.setData({
                allList: res.rows,
                filterList: res.rows,
                nextList: res.rows.filter(item => item.taskStatus !== "COMPLETE").map(item => item.id)
              })
            }
          })
        }
      })
    }
  },

  backToCase(){
    wx.navigateBack({
      delta: 1 
    });
  },

  openDetail(e: any){
    wx.navigateTo({
      url: '/pages/task/task',
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          ...e.currentTarget.dataset.item,
          nextList: this.data.nextList
        })
      }
    });
  },

  handleLoginAction(userInfo: any){
    this.setData({
      userInfo: userInfo,
      logined: true,
    })
  },

  caseHandle(data){
    const { index, filter } = data.target.dataset
    this.setData({
      active: index
    })

    let list = this.data.allList

    if(filter){
      list = list.filter(item => item.taskStatus === filter)
    }
    
    this.setData({
      filterList: list
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home?active=1`,
      "imageUrl": "/static/img/home.jpg"
    }
  }
})